/* eslint-disable eqeqeq */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
import React from 'react';
import {
  CloseCircleOutlined,
  DownloadOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Select,
  DatePicker,
  message,
  Row,
  Col,
  Modal,
  Divider,
  Dropdown,
  Menu,
  Input,
} from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import styles from '@/utils/utils.less';
import downloadFile from '@/utils/utils';
import { checkPermissions } from '@/utils/authority';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Customer from './Customer';
import TextOverFlow from '../../components/TextOverFlow';

// 客户名称
const { Option } = Select;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@Form.create()
@connect(({ oncepayns, loading }) => ({
  oncepayns,
  activeKey: oncepayns.activeKey,
  expandForm: oncepayns.expandForm,
  pageData: oncepayns.pageData,
  loading: loading.models.oncepayns,
  formFieldsValue: oncepayns.formFieldsValue,
  valuesArr: oncepayns.valuesArr,
}))
class CustomerInfoManage extends React.Component {
  state = {
    statusList: [], // 状态
    nowPage: 1,
    pageNum: 10,
    selectedRows: [],
    selectedRowKeys: [],
    supplyList: [], // 接单方列表
    formValues: {},
  };

  componentDidMount = () => {
    const {
      dispatch,
      params,
    } = this.props;
    // 获取接单方列表
    dispatch({
      type: 'oncepayns/getSupplyList',
      payload: {
        name: null,
        ...params,
      },
    }).then(res => {
      if (res.success) {
        this.setState({
          supplyList: res.data,
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });

    dispatch({
      type: 'oncepayns/getListStatus',
      payload: ['ONCE_PAY_STATUS'],
    }).then(res => {
      if (res.success && res.data) {
        res.data.ONCE_PAY_STATUS.map(status => {
          switch (status.itemCode) {
            case '1':
              return (status.statusStyle = 'default'); // 待收费
            case '2':
              return (status.statusStyle = 'success'); // 已发财务
            case '3':
              return (status.statusStyle = 'success'); // 已认领
            case '4':
              return (status.statusStyle = 'success'); // 已收费
            case '5':
              return (status.statusStyle = 'error'); // 已作废
            default:
              return (status.statusStyle = '');
          }
        });
        this.setState({ statusList: res.data.ONCE_PAY_STATUS });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
    this.getInitialList();
  };

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      activeKey,
      form,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      if (location.queryParam && location.queryParam.suppId) {
        location.queryParam.ordRecvId = location.queryParam.suppId;
      }
      if (location.queryParam && location.queryParam.suppId) {
        delete location.queryParam.suppId;
      }
      if (location.queryParam && location.queryParam.name) {
        dispatch({
          type: 'publicdata/getCustList',
          payload: [{ ordRecvId: location.queryParam.ordRecvId, name: location.queryParam.name }],
        });
        form.setFieldsValue({ ordRecvId: location.queryParam.ordRecvId });
      }
      dispatch({
        type: 'oncepayns/updateModalData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'oncepayns/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'oncepayns/updateModalData',
          payload: {
            formFieldsValue: values,
            activeKey,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true,
  ) => {
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
      });
    }

    const { dispatch } = this.props;
    const pageArg = {
      currentPage,
      pageSize,
    };
    const params = {
      ...formFieldsValue,
      pageArg,
    };
    dispatch({
      type: 'oncepayns/updateModalData',
      payload: {
        params,
        activeKey,
      },
    });

    dispatch({
      type: 'oncepayns/getList',
      payload: params,
    });
    this.setState({
      formValues: formFieldsValue,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'creName') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (key === 'createTime') {
        formFieldsValue.creStartDate =
          (tempFieldsValue.createTime &&
            tempFieldsValue.createTime[0] &&
            moment(tempFieldsValue.createTime[0]).format('YYYY-MM-DD')) ||
          null;
        formFieldsValue.creEndDate =
          (tempFieldsValue.createTime &&
            tempFieldsValue.createTime[1] &&
            moment(tempFieldsValue.createTime[1]).format('YYYY-MM-DD')) ||
          null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      delete formFieldsValue.createTime;
    });
    return formFieldsValue;
  };

  // 查看详情
  goDetails = id => {
    router.push(`/chargemanage/onebilling/detail?baseInfoId=${id}`);
  };

  // 确认
  okconfirm = e => {
    const { nowPage, pageNum } = this.state;
    const {  dispatch, formFieldsValue, activeKey } = this.props;
    dispatch({
      type: 'oncepayns/getConfirm',
      payload: { onceFeePayId: e.onceFeePayId },
    }).then(res => {
      if (res.success) {
        message.success('确认成功');
        this.searchList(this.processFormData(formFieldsValue), activeKey, nowPage, pageNum);
      } else {
        message.warning(res.message || '确认失败');
      }
    });
  };

  // 拒绝
  norefuse = e => {
    const { nowPage, pageNum } = this.state;
    const { dispatch, formFieldsValue, activeKey } = this.props;
    dispatch({
      type: 'oncepayns/getRefuse',
      payload: { onceFeePayId: e.onceFeePayId },
    }).then(res => {
      if (res.success) {
        message.success('拒绝成功');
        this.searchList(this.processFormData(formFieldsValue), activeKey, nowPage, pageNum);
      } else {
        message.success(res.message || '拒绝失败');
      }
    });
  };

  // 重置查询
  resetSearch = () => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'oncepayns/updateModalData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ createTime: null });
  };

  // 模糊搜索
  getData = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  // 查询表格布局
  toggleFormtwo = () => {
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'oncepayns/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 下载
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { activeKey } = this.props;
    const { formValues, selectedRowKeys } = this.state;
    let excel = '';
    if (activeKey == 1) {
      excel = '/nsApi/oncefeePay/exportOncePay';
    }
    const params = {
      onceFeePayIds: selectedRowKeys,
      ...formValues,
    };
    downloadFile(params, excel, 'POST');
  };

  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({
      selectedRowKeys,
      selectedRows,
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize, false);
  };

  // 标记已支付
  markPay = () => {
    const {
      dispatch,
      activeKey,
      pageData: { pagination },
      formFieldsValue,
    } = this.props;
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择标记已支付的数据');
      return;
    }
    let stateFlag;
    selectedRows.forEach(item => {
      if (+item.feeSta !== 2) {
        stateFlag = true;
      }
    });
    if (stateFlag) {
      message.warning(`所选数据非“待发财务”状态，不可操作标记已支付`);
      return;
    }
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: `已选择${selectedRowKeys.length}条数据，是否确认全部标记已支付`,
      content: '请线下和财务核实每笔费用已支付，标记后不可取消标记',
      cancelText: '取消',
      okText: '确认',
      onOk: () => {
        dispatch({
          type: 'oncepayns/markPay',
          payload: {
            onceFeeIds: selectedRowKeys,
          },
        }).then(res => {
          if (res.success) {
            if (res.data) {
              if (selectedRowKeys.length === res.data.succeeNum) {
                message.success('标记成功');
                this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize);
              } else if (selectedRowKeys.length === res.data.defeatNum) {
                Modal.error({
                  icon: <CloseCircleOutlined />,
                  title: '标记失败',
                  content: '所选数据非待发财务状态或收费方式为合并账单收费，不可标记已支付',
                  okText: '关闭',
                  okType: 'default',
                  autoFocusButton: 'cancel',
                  onOk: () => {
                    this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize);
                  },
                });
              } else {
                Modal.warning({
                  icon: <ExclamationCircleOutlined />,
                  title: `标记成功`,
                  content: `已选${selectedRowKeys.length}条数据中，${
                    res.data.succeeNum
                  }条数已标记成功，${
                    res.data.defeatNum
                  }条数据非待发财务状态或收费方式为合并账单收费，不可标记`,
                  okText: '关闭',
                  okType: 'default',
                  autoFocusButton: 'cancel',
                  onOk: () => {
                    this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize);
                  },
                });
              }
            }
            this.searchList(this.processFormData(formFieldsValue), activeKey, pagination.current, pagination.pageSize);
          } else {
            message.warning(res.message);
          }
        });
      },
    });
  };

  render() {
    const {
      activeKey,
      expandForm,
      pageData,
      loading,
      formFieldsValue,
      form: { getFieldDecorator },
    } = this.props;
    const { selectedRowKeys, supplyList, selectedRows, statusList } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns2 = [
      {
        title: '接单方',
        dataIndex: 'ordRecvName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '产品名称',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '业务年月',
        dataIndex: 'busiYm',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => `${`${val}`.substring(0, 4)}-${`${val}`.substring(4)}`,
      },
      {
        title: '收费总金额',
        dataIndex: 'feeAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: feeAmo => (feeAmo === 0 ? 0 : (feeAmo && feeAmo) || '--'),
      },
      {
        title: '状态',
        dataIndex: 'feeStaName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '收费方式',
        dataIndex: 'feeWayName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => moment(val).format('YYYY-MM-DD HH:mm') || '无',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => {
          if (record.feeSta == 1) {
            // 待收费
            return (
              <span>
                <a
                  onClick={() =>
                    router.push(`/paymanage/oncepayns/detail?onceFeePayId=${record.onceFeePayId}`)
                  }
                >
                  查看
                </a>
                <Divider type="vertical" />
                <Dropdown
                  overlay={
                    <Menu>
                      {record.feeSta == 1 ? (
                        <Menu.Item key="ok" onClick={() => this.okconfirm(record)}>
                          确认
                        </Menu.Item>
                      ) : null}
                      {record.feeSta == 1 ? (
                        <Menu.Item key="on" onClick={() => this.norefuse(record)}>
                          拒绝
                        </Menu.Item>
                      ) : null}
                    </Menu>
                  }
                >
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              </span>
            );
          }
          if (record.feeSta == 2) {
            return (
              <span>
                <a
                  onClick={() =>
                    router.push(`/paymanage/oncepayns/detail?onceFeePayId=${record.onceFeePayId}`)
                  }
                >
                  查看
                </a>
              </span>
            );
          }
          return (
            <a
              onClick={() =>
                router.push(`/paymanage/oncepayns/detail?onceFeePayId=${record.onceFeePayId}`)
              }
            >
              查看
            </a>
          );
        },
      },
    ];

    // 状态
    const signWayOptionsList = statusList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    const renderAdvancedFormtwo = (
      <div>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>
            <Form layout="inline">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayout} label="接单方" style={{ display: 'block' }}>
                    {getFieldDecorator('ordRecvId', {
                      rules: [{ required: false }],
                      initialValue: formFieldsValue.ordRecvId,
                    })(
                      <Select
                        placeholder="请输入关键字检索"
                        showSearch
                        optionFilterProp="children"
                        notFoundContent="暂无数据"
                        onSelect={(value, options) => this.getData(value, options)}
                        allowClear
                      >
                        {supplyList.map(item => (
                          <Option key={item.suppId} title={item.name}>
                            {item.name}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayout} label="状态" style={{ display: 'block' }}>
                    {getFieldDecorator('feeSta', {
                      rules: [{ required: false, message: '请输入' }],
                      initialValue: formFieldsValue.feeSta,
                    })(
                      <Select
                        placeholder="请输入关键字检索"
                        allowClear
                        showSearch
                        optionFilterProp="children"
                      >
                        {signWayOptionsList}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem>
                    <Button
                      type="primary"
                      style={{ marginRight: 8 }}
                      onClick={() => this.searchBtnList(activeKey)}
                    >
                      查询
                    </Button>
                    <Button onClick={this.resetSearch}>重置</Button>
                    <a style={{ marginLeft: 8 }} onClick={this.toggleFormtwo}>
                      展开 <DownOutlined />
                    </a>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </div>
        </Card>
        <Card className={styles.tableCard}>
          <Button
            onClick={this.export}
            type="primary"
            icon={<DownloadOutlined />}
            style={{ margin: '0 8px 16px 0' }}
          >
            导出
          </Button>
          {checkPermissions('ns:oncefeePay:collectFee') && (
            <Button onClick={this.markPay}>标记已支付</Button>
          )}

          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            selectedRowKeys={selectedRowKeys}
            data={pageData}
            columns={columns2}
            rowKey="onceFeePayId"
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </div>
    );

    const 
    renderSimpleFormtwo = (
      <div>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>
            <Form layout="inline">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayout} label="接单方" style={{ display: 'block' }}>
                    {getFieldDecorator('ordRecvId', {
                      initialValue: formFieldsValue.ordRecvId,
                      rules: [{ required: false }],
                    })(
                      <Select
                        placeholder="请输入关键字检索"
                        showSearch
                        optionFilterProp="children"
                        notFoundContent="暂无数据"
                        onSelect={(value, options) => this.getData(value, options)}
                        allowClear
                      >
                        {supplyList.map(item => (
                          <Option key={item.suppId} title={item.name}>
                            {item.name}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayout} label="状态" style={{ display: 'block' }}>
                    {getFieldDecorator('feeSta', {
                      initialValue: formFieldsValue.feeSta,
                      rules: [{ required: false, message: '请输入' }],
                    })(
                      <Select
                        placeholder="请输入关键字检索"
                        allowClear
                        showSearch
                        optionFilterProp="children"
                      >
                        {signWayOptionsList}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayout} label="客户名称" style={{ display: 'block' }}>
                    {getFieldDecorator('custId', {
                      initialValue: formFieldsValue.custId,
                      rules: [{ required: false }],
                    })(<Customer getData={this.getData} allowClear />)}
                  </FormItem>
                </Col>
              </Row>

              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem label="创建日期" {...formItemLayout} style={{ display: 'block' }}>
                    {getFieldDecorator('createTime', {
                      initialValue: formFieldsValue.createTime,
                      rules: [{ type: 'array', required: false }],
                    })(
                      <RangePicker
                        placeholder={['开始日期', '结束日期']}
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                      />
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem label="创建人" {...formItemLayout} style={{ display: 'block' }}>
                    {getFieldDecorator('creName', {
                      rules: [{ required: false, message: '请输入' }],
                      initialValue: formFieldsValue.creName,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <span style={{ float: 'right' }}>
                    <Button
                      type="primary"
                      style={{ marginRight: 8 }}
                      onClick={() => this.searchBtnList(activeKey)}
                    >
                      查询
                    </Button>
                    <Button onClick={this.resetSearch}>重置</Button>
                    <a style={{ marginLeft: 8 }} onClick={this.toggleFormtwo}>
                      收起 <UpOutlined />
                    </a>
                  </span>
                </Col>
              </Row>
            </Form>
          </div>
        </Card>
        <Card className={styles.tableCard}>
          <Button
            onClick={this.export}
            type="primary"
            icon={<DownloadOutlined />}
            style={{ margin: '0 8px 16px 0' }}
          >
            导出
          </Button>
          {checkPermissions('ns:oncefeePay:collectFee') && (
            <Button onClick={this.markPay}>标记已支付</Button>
          )}
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            selectedRowKeys={selectedRowKeys}
            data={pageData}
            columns={columns2}
            rowKey="onceFeePayId"
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </div>
    );
    // 获取页签组件
    const renderFormtwo = expandForm ? renderSimpleFormtwo : renderAdvancedFormtwo ;
    // eslint-disable-next-line no-shadow
    const getTabPane = activeKey => {
      if (activeKey == 2) {
        return renderFormtwo;
      }
      return <div />;
    };
    return <PageHeaderWrapper>{getTabPane(2)}</PageHeaderWrapper>;
  }
}
// eslint-disable-next-line no-class-assign
CustomerInfoManage = Form.create({})(CustomerInfoManage);
export default CustomerInfoManage;
